package edu.gduf.utils;

import org.springframework.stereotype.Repository;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * Jedis连接工具
 * @author kgy
 */
@Repository
public class JedisUtil {

    private static ShardedJedisPool jp = null; // Jedis连接池
    private static String host = null;
    private static String password = null;
    private static int port;
    private static int maxTotal;
    private static int maxTdle;

    static {
        ResourceBundle rb = ResourceBundle.getBundle("redis");
        host = rb.getString("redis.host");
        password = rb.getString("redis.password");
        port = Integer.parseInt(rb.getString("redis.port"));
        maxTotal = Integer.parseInt(rb.getString("redis.maxTotal"));
        maxTdle = Integer.parseInt(rb.getString("redis.MaxTdle"));
        JedisPoolConfig jpc = new JedisPoolConfig();
        jpc.setMaxTotal(maxTotal);
        jpc.setMaxIdle(maxTdle);
        JedisShardInfo jedisShardInfo = new JedisShardInfo(host,port);
        jedisShardInfo.setPassword(password);
        List<JedisShardInfo> list = new LinkedList<JedisShardInfo>();
        list.add(jedisShardInfo);
        jp = new ShardedJedisPool(jpc,list);
    }

    /**
     * 获取Jedis连接池对象
     * @return
     */
    public static ShardedJedis getResource(){
        return jp.getResource();
    }

    /**
     * 删除key
     */
    public void delete(String key){
        getResource().del(key);
    }

    /**
     * 是否存在key
     * @param key
     * @return
     */
    public boolean hasKey(String key){
        return getResource().exists(key);
    }

    /**
     * 设置过期时间
     * @param key
     * @param seconds
     * @return
     */
    public Long expire(String key, Integer seconds){
        return getResource().expire(key,seconds);
    }

    public String set(String key, String value){
        return getResource().set(key,value);
    }
}
